package com.xjoyt.pay.operater.services;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import com.xjoyt.pay.abstracts.AbstractService;
import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.dto.PageParam;
import com.xjoyt.pay.dto.PageResult;
import com.xjoyt.pay.operater.auth.params.RolePageParam;
import com.xjoyt.pay.operater.auth.po.Role;
import com.xjoyt.pay.operater.auth.po.RoleNode;
import com.xjoyt.pay.operater.repository.RoleNodeRepository;
import com.xjoyt.pay.operater.repository.RoleRepository;

@Service
public class RoleService extends AbstractService {

	@Autowired
	private RoleRepository repository;

	@Autowired
	private RoleNodeRepository roleNodeRepository;

	public Role get(String id) {
		// TODO Auto-generated method stub
		return repository.findOne(id);
	}

	public PageResult<Role> loadPage(PageParam<RolePageParam> param) {
		return repository.loadPage(param);
	}

	public ExecuteResult<Role> save(Role entity) {
		if (entity.addedDate == null)
			entity.addedDate = new Date();
		entity = repository.save(entity);
		return ExecuteResult.ok(entity);
	}

	public ExecuteResult<?> delete(String id) {
		repository.delete(id);
		return ExecuteResult.ok();
	}

	public ExecuteResult<?> saveNode(String id, List<String> nodeList) {
		Role role = repository.findOne(id);
		if (role == null)
			return ExecuteResult.fail("数据不存在");
		if (CollectionUtils.isNotEmpty(role.nodeList))
			role.nodeList.forEach(item -> roleNodeRepository.delete(item.id));

		for (String item : nodeList) {
			RoleNode entity = new RoleNode();
			entity.nodeId = item;
			entity.role = role;
			roleNodeRepository.save(entity);
		}

		return ExecuteResult.ok();
	}

	public List<Role> findAll(@RequestBody RolePageParam param) {
		return repository.findAll(param);
	}
}
